package com.yuexun.dhdoctor.module.email.model.impl;


import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.email.model.IUploadModel;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by work-jx on 2016/8/29.
 */
public class UploadModel implements IUploadModel {
    private static final OkHttpClient client = new OkHttpClient.Builder()
            //设置超时，不设置可能会报异常
            .connectTimeout(1000, TimeUnit.MINUTES)
            .readTimeout(1000, TimeUnit.MINUTES)
            .writeTimeout(1000, TimeUnit.MINUTES)
            .build();

    @Override
    public Observable uploadFile(final String path) {
        return Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(final Subscriber<? super Object> subscriber) {
                File file = new File(path);
                //构造上传请求，类似web表单
                RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("hello", "android")
                        .addFormDataPart("photo", file.getName(), RequestBody.create(null, file))
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"" + file.getName() + "\""), RequestBody.create(MediaType.parse("application/octet-stream"), file))
                        .build();

                //进行包装，使其支持进度回调
                final Request request = new Request.Builder().url(AppConfig.WEB_FILE_UPLOAD)
                        .post(requestBody)
                        .build();
                //开始请求
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        subscriber.onError(e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        subscriber.onNext(response.body().string());
                        subscriber.onCompleted();
                    }
                });

            }
        });
    }
}
